package com.atguigu.gmall.order.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.config.mq.MqService;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
public class OrderCloseListener {

    @Autowired
    OrderBizService orderBizService;
    @Autowired
    MqService mqService;
    //监听死信队列中所有待关闭的订单
    @RabbitListener(queues = MqConst.ORDER_DEAD_QUEUE)
    public void listener (Message message, Channel channel) throws IOException {
        //消息的标签，唯一性，区别消息的
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String content = new String(message.getBody());//消息内容
        try {
            log.info("收到需要关单的消息：{}",content);
            //将消息由 json 转为 OrderInfo对象
            OrderInfo orderInfo = JSON.parseObject(content, OrderInfo.class);
            //进行关单操作
            orderBizService.closeOrder(orderInfo.getId(),orderInfo.getUserId());

            //int i = 10/0;//模拟关单发生异常

            //消费端 收到消息 回复ack
            channel.basicAck(deliveryTag,false);
        } catch (Exception e){
            //消费失败，重试5次重新入队，5次后等待人工处理

            //1 导致 无限次数 入队消费，cpu压满
            //log.info("消费失败，需要重新入队");
            //channel.basicNack(deliveryTag,false,true);;// true消息重新入队

            //2 有限次数重试
            mqService.retry(channel,deliveryTag,content,5);
        }
    }
}
